/*
 * @作者: Fultom
 * @创建时间: 2021-10-27 16:57:10
 * @最近修改时间: 2025-07-10 10:11:29
 * @功能:
 */

import { AppNavigate, PATH_LOGIN } from '@/pagePath'
import moment from 'moment'
import { StorageKey } from './constant'

export class AppDebounce {
  /**
   * @param func 用户传入的防抖函数
   * @param delay 延迟时间，单位ms
   * @param immediate 是否默认执行一次(第一次不延迟)
   */
  static use = (func: Function, delay: number = 50, immediate: boolean = false): Function => {
    let timer: number | undefined | null
    return (...args: any) => {
      if (timer) clearInterval(timer)
      if (immediate) {
        if (!timer) func.apply(this, args)
        timer = setTimeout(() => {
          //n 秒内 多次触发事件,重新计算.timeer
          timer = null //n 秒内没有触发事件 timeer 设置为null，保证了n 秒后能重新触发事件 flag = true = !timmer
        }, delay)
      } else {
        timer = setTimeout(() => {
          func.apply(this, args)
        }, delay)
      }
    }
  }
}

/** toast 提醒 */
export const AppToast = (
  title: string = '',
  icon: 'success' | 'loading' | 'fail' | 'none' | undefined = 'none',
  confirmAction?: () => void,
) => {
  if (title.length > 16) {
    AppShowModal({
      message: title,
      showCancel: false,
      confirmAction: confirmAction,
    })
  } else {
    return uni.showToast({
      title: title,
      duration: 1500,
      icon: icon,
    })
    // AppDebounce.use(() => {
    //     uni.showToast({
    //         title: title,
    //         duration: 2500,
    //         icon: icon
    //     })
    /* #ifdef MP-TOUTIAO */
    // tt.showToast({
    //     title: title,
    //     duration: 2500,
    //     icon: icon
    // })
    /* #endif */
    // }, 2500, true)
  }
}

/** 显示模态弹窗 */
export const AppShowModal = (option: {
  title?: string
  message?: string
  showCancel?: boolean
  cancelText?: string
  confirmText?: string
  confirmAction?: () => void
  cancelAction?: () => void
}) => {
  uni.showModal({
    title: option.title,
    content: option.message,
    showCancel: option.showCancel,
    cancelText: option.cancelText || '取消',
    confirmText: option.confirmText || '确定',
    success: (res) => {
      if (res.confirm && option.confirmAction != undefined) {
        option.confirmAction()
      } else if (res.cancel) {
        if (option.cancelAction != undefined) {
          option.cancelAction()
        }
      }
    },
  })
}

/** 获取网络类型 */
export const AppGetNetworkType = () => {
  return new Promise<string>((res, rej) => {
    uni.getNetworkType({
      success: ({ networkType }) => {
        res(networkType)
      },
      fail: () => {
        rej('获取失败')
      },
    })
  })
}

/** 将 data 存储在本地缓存中指定的 key 中，会覆盖掉原来该 key 对应的内容，这是一个同步接口。 */
export const AppSetStorageSync = (key: string, data: any): void => {
  uni.setStorageSync(key, data)
}

/** 从本地缓存中同步获取指定 key 对应的内容 */
export const AppGetStorageSync = <T>(key: string): T => {
  try {
    const value = uni.getStorageSync(key)
    return value
  } catch (e) {
    console.log(`获取${key},失败`)
    return {} as T
  }
}

/** 同步清理本地数据缓存 */
export const AppClearStorageSync = () => {
  try {
    uni.clearStorageSync()
  } catch (e) {
    console.log(`清除storage-失败`)
  }
}

/** 从本地缓存中异步移除指定 key */
export const AppRemoveStorageSync = (key: string) => {
  try {
    uni.removeStorageSync(key)
  } catch (e) {
    console.log(`清除${key},失败`)
  }
}

/** 更新 */
export const AppUpdateListener = () => {
  const updateManager = uni.getUpdateManager()
  updateManager.onCheckForUpdate(function (res) {
    // 请求完新版本信息的回调
    console.log(res.hasUpdate)
  })

  updateManager.onUpdateReady((res) => {
    AppShowModal({
      title: '更新提示',
      message: '新版本已经准备好，请使用新版本',
      showCancel: false,
      confirmText: '重新启动',
      confirmAction: () => {
        updateManager.applyUpdate()
      },
    })
  })
}

/**
 * 防抖   跳转到 登录
 * @param {提示文案} title
 * @param {时间} pushTiem
 */
export class AppWaitThenGoToLogin {
  static use = (title = '需要您先登陆', pushTiem = 2000, isSavePath = true) => {
    if (isSavePath) {
      const pages = getCurrentPages()
      const currentPage: any = pages[pages.length - 1]
      const urlTemp: string = currentPage.route
      const url = urlTemp.startsWith('/') ? urlTemp : `/${urlTemp}`
      const options = currentPage.options
      AppToast(title)
      let urlWithArgs = url + '?'
      for (const key in options) {
        const value = options[key]
        urlWithArgs += key + '=' + value + '&'
      }
      urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
      AppSetStorageSync(StorageKey.loginBeforePage, urlWithArgs)
    }
    setTimeout(() => {
      AppNavigate.push(PATH_LOGIN.Login)
    }, pushTiem)
  }
}

/** 日期格式化 */
export const dateFormat = (time: number): any => {
  if (!time) return ''
  return moment(time * 1000).format('YYYY-MM-DD HH:mm:ss')
}
/** 倒计时 */
export const getRemainTime = (time: number): any => {
  if (time) {
    const hours = Math.floor(time / 60 / 60)
    const min = Math.floor((time / 60) % 60)
    const second = Math.floor(time % 60)
    return `${hours < 10 ? `0${hours}` : hours}:${min < 10 ? `0${min}` : min}:${second < 10 ? `0${second}` : second
      }`
  } else {
    return '00:00:00'
  }
}
/** 倒计时时分秒   type  0：天  1：时  2：分  3：秒 */
export const getRemainPartTime = (time: number, type: number): any => {
  if (time) {
    const days = Math.floor(time / 60 / 60 / 24)
    const hours = Math.floor(days / 60 / 60)
    const min = Math.floor((time / 60) % 60)
    const second = Math.floor(time % 60)
    if (type == 0) {
      return `${days}`
    } else if (type == 1) {
      return `${hours < 10 ? `0${hours}` : hours}`
    } else if (type == 2) {
      return `${min < 10 ? `0${min}` : min}`
    } else if (type == 3) {
      return `${second < 10 ? `0${second}` : second}`
    }
  } else {
    return ''
  }
}
/** 校验手机号 */
export const checkPhoneNumber = (phoneNumber: string, intlAreaCode = 86): boolean => {
  const PhoneReg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/
  if (intlAreaCode === 86) {
    if (!PhoneReg.test(phoneNumber)) {
      return false
    } else {
      return true
    }
  } else {
    if (phoneNumber.length < 6) {
      return false
    } else {
      return true
    }
  }
}
/** 6~12位数字与字母组合密碼 */
export const checkPassword = (password: string): boolean => {
  const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/
  if (!reg.test(password)) {
    return false
  } else {
    return true
  }
}
